<template>
  <!-- 预处理算法环境镜像管理 -->
  <div class="model-manage">
    <div class="mm-panel-wrapper-left">
      <Tree ref="leftTreeRef" :isImageManagement="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_15"
        :folderMenu="right_menuList.rightMenuList_16" :fileMenu="right_menuList.rightMenuList_17"
        :treeData="ownTreeData" :currentNodeKey="currentNodeKey" :defaultExpandedKeys="defaultExpandedKeys"
        @handleAddNode="handleAddModel" @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick"
        @nodeDelete="handleNodeDelete" @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
      </Tree>
    </div>
    <div class="mm-divider"></div>
    <div class="mm-panel-wrapper-right">
      <div class="padding20">
        <div class="mm-panel-title mb-10">
          镜像基本信息
          <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
        </div>
        <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="imageName">
                <el-input v-model="itemForm.imageName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建日期" prop="createTime">
                <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传镜像" prop="imagePath">
                <el-button type="primary" @click="uploadFile">上传</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="描述" prop="imageDescription">
            <el-input type="textarea" v-model="itemForm.imageDescription"></el-input>
          </el-form-item>
        </el-form>
        <div class="mm-panel-title mb-10">
          镜像状态
        </div>
        <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
          <el-form-item label="镜像地址" prop="repositoryPath">
            <el-input v-model="itemForm.repositoryPath" readonly></el-input>
          </el-form-item>
          <el-form-item label="镜像大小" prop="imageSize">
            <el-input v-model="itemForm.imageSize" readonly></el-input>
          </el-form-item>
          <el-form-item label="当前阶段" prop="imageStatus">
            <!-- <el-input v-model="itemForm.imageStatus" readonly></el-input> -->
            <el-select v-model="itemForm.imageStatus" disabled>
              <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- @selection-change="handleSelectionChange" -->
        <!-- <el-table v-loading="loading" :data="tableData">
          <el-table-column label="序号" type="index" width="50" align="center">
            <template slot-scope="scope">
              <span>{{
                (queryParams.pageNum - 1) * queryParams.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
</el-table-column>
<el-table-column label="名称" align="center" prop="imageName" :show-overflow-tooltip="true" width="200" />
<el-table-column label="镜像地址" align="center" prop="imagePath" :show-overflow-tooltip="true" width="200" />
<el-table-column label="镜像仓库路径" align="center" prop="imageRegistryPath" :show-overflow-tooltip="true" width="120" />
<el-table-column label="镜像描述" align="center" prop="imageDescription" :show-overflow-tooltip="true" />
<el-table-column label="创建时间" align="center" prop="createTime" width="160" />
<el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
  <template #default="{ row }">
              <el-dropdown @command="(cmd) => handleCommand(cmd, row)">
                <el-button type="primary">
                  <i class="el-icon-more"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="编辑">编辑</el-dropdown-item>
                  <el-dropdown-item command="删除">删除</el-dropdown-item>
                  <el-dropdown-item command="下载">下载</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
</el-table-column>
</el-table> -->
      </div>
    </div>
    <PerceptionSampleDialog :visible.sync="openDialog" :data="editingRow" :sampleSetId="currentNodeKey"
      @submit="addSubmit" />
    <AddOrUpdateFolder v-if="isAddOrUpdateFolder" :preSetType="1" ref="addOrUpdateFolderRef" @refresh="getList">
    </AddOrUpdateFolder>
    <AddOrUpdateModel v-if="isAddOrUpdateModel" :preSetType="1" ref="addOrUpdateModelRef" @refresh="getList">
    </AddOrUpdateModel>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import {
  getTreeApi,
  deleteTreeApi,
  moveTreeApi,
  getImageManageApi,
  updateImageManageApi,
  getImageDetailsApi
} from "@/api/myspace/preprocessing/index";

import {
  addListApi,
  deleteListApi,
  updateListApi,
  downloadListApi,
} from "@/api/myspace/preprocessing/environmentMirror";

import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";
import PerceptionSampleDialog from "./components/PerceptionSampleDialog.vue";
import { error } from "jquery";

export default {
  data() {
    return {
      // -1=未上传 0=已上传 2=已加载 3=推送中 4=已推送 5=加载失败 6=推送失败 7=删除失败 8=其他失败
      stateList: [
        {
          label: "未上传",
          value: -1
        },
        {
          label: "已上传",
          value: 0
        },
        {
          label: "加载中",
          value: 1
        },
        {
          label: "已加载",
          value: 2
        },
        {
          label: "推送中",
          value: 3
        },
        {
          label: "已推送",
          value: 4
        },
        {
          label: "加载失败",
          value: 5
        },
        {
          label: "推送失败",
          value: 6
        },
        {
          label: "删除失败",
          value: 7
        },
        {
          label: "其他失败",
          value: 8
        },
      ],
      itemForm: {
        imageId: '',
        imageName: "", //名称
        createTime: "",
        imagePath: "", //路径
        imageDescription: "", //描述
        repositoryPath: "",//镜像地址
        imageSize: "",//大小
        imageStatus: 0,
      },
      rules: {
        name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
      },
      openDialog: false,
      loading: true,
      tableData: [],
      queryParams: {
        // 查询参数
        pageNum: 1,
        pageSize: 10,
        name: "",
        modelId: "",
        folderId: "",
      },
      isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
      isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
      isFolder: false, // 是否展示文件夹详情
      isFile: false, // 是否展示文件详情
      isModel: false, //是否是模型详情
      isModelGroupDetail: false, // 是否展示模型组详情,
      selectedNodeInfo: {}, // 当前选中节点的信息
      ownTreeData: [], // 本账户模型列表
      currentNodeKey: 0, // 当前选中节点的key
      defaultExpandedKeys: [], // 默认展开的节点
      openDialog: false,
      editingRow: null, // 存储正在编辑的行数据
    };
  },
  components: {
    Tree,
    AddOrUpdateModel,
    AddOrUpdateFolder,
    PerceptionSampleDialog,
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.modelManageTool.right_menuList,
      selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
      expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
      userId: (state) => state.user.id,
    }),
  },
  async created() {
    await this.getList();
    this.currentNodeKey = this.selectedNodeId;
    this.defaultExpandedKeys = this.expandedNodeIds;
    this.$nextTick(() => {
      this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
      const params = {
        id: this.currentNodeKey,
      };
      this.nodeClick(params);
    });
  },
  mounted() {
    // 上传文件组件
    this.$EventBus.$on("fileSuccess", (response) => {
      if (response.code != 200) {
        this.$message.error(response.msg);
        return;
      }
      this.$message.success("上传成功");
      this.itemForm.imagePath = response.data.filePath;
      this.itemForm.imageSize = response.data.fileSize;
    });
  },
  methods: {
    uploadFile() {
      this.$EventBus.$emit("openUploader", {
        token: getToken(),
        prefixFlag: 1,
        userId: this.$store.state.user.id,
      });
    },
    //获取详情
    getDetail() {
      getImageDetailsApi(this.itemForm.imageId).then((response) => {
        this.itemForm = response.data;
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    // 保存
    async handleSave() {
      const res = await updateImageManageApi(this.itemForm);
      if (res.code === 200) {
        this.$message.success("保存成功");
        this.getDetail()
      } else {
        this.$message.error(res.msg);
      }
    },
    // 上传文件组件
    uploadBus() {
      // 模拟用户选择的文件
      // const file = new File(["file content"], "filename.txt", { type: "text/plain" });
      // 打开文件选择框
      this.$EventBus.$emit("openUploader", {
        token: getToken(),
        prefixFlag: 4,
        userId: this.userId,
        // fileObject: file
      });
    },
    handleCommand(command, row) {
      switch (command) {
        // case "详情":
        //   break;

        case "编辑":
          this.editingRow = row;
          this.openDialog = true;
          break;
        case "删除":
          this.delTableData(row);
          break;

        case "下载":
          this.downloadTableData(row);
          break;

        default:
          break;
      }
    },
    //新增
    handleAdd() {
      this.editingRow = null; // 清空编辑状态
      this.openDialog = true;
    },
    async getList(newNodeId) {
      //预处理类型 1=镜像管理，2=在线开发运行，3=算子管理，4=任务流管理
      const params = { preSetType: 1 };
      const res = await getTreeApi(params);
      if (res.code == 200 && Array.isArray(res.data)) {
        this.ownTreeData = res.data.length > 0 ? res.data[0].commonTreeList : [];
        const targetId = newNodeId || this.selectedNodeId;
        const targetnode = targetId
          ? this.recurNodeForTarget(this.ownTreeData, targetId)
          : this.ownTreeData[0];
        this.nodeClick(targetnode);
      }
    },

    // 表格
    async addSubmit(formData) {
      const api = formData.id
        ? updateListApi // 编辑
        : addListApi; // 新增

      const res = await api(formData);
      if (res.code === 200) {
        this.$message.success(res.msg);
        this.loading = true;
        // this.getTableData(params);
        this.openDialog = false;
      } else {
        this.$message.error(res.msg);
      }
    },
    async delTableData(row) {
      const res = await deleteListApi(row.id);
      if (res.code == 200) {
        this.$message.success(res.msg);
      }
    },

    async downloadTableData(row) {
      try {
        const res = await downloadListApi({ imageId: row.id });
        const blob = res.data;
        const header = res.headers["content-disposition"];
        const fileName =
          this.extractFilename(header) || "perception-sample.zip";
        // 下载
        // const blob = new Blob([res], { type: "application/x-zip-compressed" });
        const downloadUrl = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error(error);
      }
    },

    extractFilename(contentDisposition) {
      if (!contentDisposition) {
        return null;
      }

      // 匹配 filename="xxx" （推荐格式，支持包含空格和特殊字符）
      const filenameMatch = contentDisposition.match(
        /filename\s*=\s*"([^"]+)"/i
      );
      if (filenameMatch) {
        return filenameMatch[1];
      }

      // 匹配 filename=xxx （不带引号的简单格式）
      const filenameSimpleMatch = contentDisposition.match(
        /filename\s*=\s*([^;\s]+)/i
      );
      if (filenameSimpleMatch) {
        return filenameSimpleMatch[1];
      }

      return null;
    },

    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    // 新增文件夹
    handleAddOrUpdateFolder(sign, node) {
      this.isAddOrUpdateFolder = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateFolderRef"].init(
          sign,
          node,
          this.ownTreeData,
          "account"
        );
      });
    },
    // 新增镜像
    handleAddModel(node) {
      this.isAddOrUpdateModel = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateModelRef"].init(undefined, node);
      });
    },
    // 点击树节点，右侧展示详细信息
    async nodeClick(node) {
      if (node == undefined) {
        return;
      }
      this.selectedNodeInfo = node;
      this.currentNodeKey = node.id;
      this.$nextTick(() => {
        this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
      });
      this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", {
        moduleName: "model",
        id: node.id,
      });
      if (!node.data) return;

      if (node.type == 0) {
        // 点击的文件夹
        this.isFolder = true;
        this.isModel = false;
        this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", {
          moduleName: "model",
          idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])),
        });
      } else {
        // 点击的文件
        this.isFolder = false;
        this.isFile = true;
        this.isModel = true;
        const res = await getImageManageApi({
          preSetId: node.id
        });
        if (res.code === 200) {
          this.itemForm = res.data
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    /**
     * 树节点删除事件的回调
     * @param node 被删除的节点
     */
    handleNodeDelete(node) {
      this.$confirm(
        `确定删除${node.type == 0 ? "目录" : "镜像"}  ${node.data.name} ?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          customClass: "message-box-style",
          type: "warning",
        }
      )
        .then(async () => {
          const response = await deleteTreeApi(node.id, 1);
          if (response.code == 200) {
            this.$message.success(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "success"
              )
            );
            if (node.id == this.currentNodeKey) {
              this.isFolder = false;
              this.isModel = false;
            }
            this.getList();
          }
        })
        .catch(() => { });
    },
    /**
     * 树节点复制事件的回调
     * @param node 被复制的节点
     */
    // handleCopyFile(node) {
    //   addModel({
    //     modelName: node.data.modelName + " Copy",
    //     modelEnglishName: node.data.modelEnglishName + " Copy",
    //     modelAlias: node.data.modelAlias + " Copy",
    //     parentId: node.data.parentId,
    //     nodeType: node.type, // 0表示文件夹，1表示文件
    //     categoryLabel: node.data.categoryLabel,
    //     modelResolution: node.data.modelResolution,
    //     modelDescription: node.data.modelDescription,
    //     modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
    //     userId: node.data.userId,
    //   }).then((response) => {
    //     if (response.code == 200) {
    //       this.$message.success(
    //         this.$toolHandle.getI18nName(
    //           this.$zh.setup.responseText,
    //           this.$en.setup.responseText,
    //           this.$i18n.locale,
    //           "success"
    //         )
    //       );
    //       this.getList();
    //     }
    //   });
    // },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      moveTreeApi({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getList();
        }
      });
    },
    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      switch (menu.name) {
        case "新增镜像":
          this.handleAddModel(node);
          break;
        case "新增分类":
          this.handleAddOrUpdateFolder("add");
          break;
        case "添加子目录":
          this.handleAddOrUpdateFolder("add", node);
          break;
        case "编辑":
          this.handleAddOrUpdateFolder("edit", node);
          break;
        // case "复制":
        //   // 文件的复制
        //   this.handleCopyFile(node);
        //   break;
        case "删除":
          // 文件夹/文件的删除
          this.handleNodeDelete(node);
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.model-manage {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;

  .mm-panel-wrapper-left {
    width: 300px;
    height: 100%;
    flex-grow: 0;
    flex-shrink: 0;
    display: flex;
    position: relative;
    padding: 0 10px;
  }

  .mm-divider {
    width: 1px;
    height: auto;
    flex-grow: 0;
    position: relative;
    align-self: stretch;
    background-color: var(--ui-border-color-split);
  }

  .mm-panel-wrapper-right {
    width: 256px;
    height: 100%;
    min-width: 0px;
    flex-grow: 1;
    flex-shrink: 1;
    display: flex;
    position: relative;
    overflow: auto;
  }
}

.padding20 {
  padding: 20px;
  width: 100%;
}
</style>
